
/**
 *
 * @author group_0217
 */
public class File extends Data {
    // The files in the file system.

    // The contents of the File.
    private String Contents;

    /**
     * Create a File object with name.
     * @param name the name of the File.
     */
    public File(String name) {
        super(name);
        // Initialize the contents.
        Contents = "";
    }

    /**
     * Display the contents of the current file.
     */
    public void display() {
        System.out.println(Contents);
    }

    /**
     * Append a string to the contents of the current file.
     * @param s the String to be appended to the File.
     */
    public void append(String s) {

        Contents = Contents + s + '\n';
    }

    /**
     * Overwrite the contents of the current file with the string s.
     * @param s the String to overwrite the contents of the File.
     */
    public void overwrite(String s) {

        Contents = s + '\n';
    }

    /**
     * Give a copy of object File
     * @return newFile, the new copied File
     */
    @Override
    public File copy() {
        // Return a new copy of File object
        File newFile = new File(this.returnName());
        newFile.Contents = this.Contents;
        return newFile;
    }

    /**
     * 
     * @return the Contents of the File.
     */
    public String returnContents() {
        return Contents;
    }

    /**
     * Display the File name.
     */
    @Override
    public void list() {
        System.out.println(this.returnName() + '\n');
    }

    /**
     * 
     * @param regex the String to be checked if contained in any line of the File.
     * @return the lines that contain the regex.
     */
    @Override
    public String grep(String regex) {
        if (!this.Contents.contains(regex)) {
            // If the contents of the File do not have regex.
            return "";
        } else {
            // Spilt the lines.
            String[] lines = Contents.split("\n");
            String toPrint = "";
            for (String i : lines) {
                // If the line contains regex.
                if (i.contains(regex)) {
                    toPrint = toPrint + i + '\n';
                }
            }
            return toPrint;
        }
    }
}
